#!/bin/bash

# API测试脚本

set -e

BASE_URL="http://localhost:3000"
API_BASE="$BASE_URL/api/v1"

echo "🧪 Rust Web服务API测试脚本"
echo "=========================="

# 检查服务是否运行
echo "🔍 检查服务状态..."
if ! curl -s "$BASE_URL/health" > /dev/null; then
    echo "❌ 服务未运行，请先启动服务"
    exit 1
fi
echo "✅ 服务运行正常"

echo ""

# 测试健康检查
echo "1. 测试健康检查..."
curl -s "$BASE_URL/health" | jq .
echo ""

# 测试用户注册
echo "2. 测试用户注册..."
REGISTER_RESPONSE=$(curl -s -X POST "$API_BASE/auth/register" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "email": "test@example.com",
    "password": "password123",
    "confirm_password": "password123",
    "full_name": "Test User"
  }')

echo "$REGISTER_RESPONSE" | jq .
echo ""

# 测试用户登录
echo "3. 测试用户登录..."
LOGIN_RESPONSE=$(curl -s -X POST "$API_BASE/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email_or_username": "test@example.com",
    "password": "password123"
  }')

echo "$LOGIN_RESPONSE" | jq .

# 提取访问令牌
ACCESS_TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.data.access_token')
if [ "$ACCESS_TOKEN" = "null" ] || [ -z "$ACCESS_TOKEN" ]; then
    echo "❌ 登录失败，无法获取访问令牌"
    exit 1
fi

echo ""
echo "✅ 登录成功，访问令牌: ${ACCESS_TOKEN:0:20}..."

# 测试获取当前用户信息
echo "4. 测试获取当前用户信息..."
curl -s -X GET "$API_BASE/auth/me" \
  -H "Authorization: Bearer $ACCESS_TOKEN" | jq .
echo ""

# 测试获取用户列表（需要管理员权限）
echo "5. 测试获取用户列表..."
curl -s -X GET "$API_BASE/users" \
  -H "Authorization: Bearer $ACCESS_TOKEN" | jq .
echo ""

# 测试更新用户信息
echo "6. 测试更新用户信息..."
curl -s -X POST "$API_BASE/users/$(echo "$LOGIN_RESPONSE" | jq -r '.data.user.id')" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "full_name": "Updated Test User"
  }' | jq .
echo ""

# 测试监控指标
echo "7. 测试监控指标..."
curl -s "$BASE_URL/metrics" | head -20
echo ""

echo "✅ API测试完成！"
echo ""
echo "📊 测试总结："
echo "   - 健康检查: ✅"
echo "   - 用户注册: ✅"
echo "   - 用户登录: ✅"
echo "   - 获取用户信息: ✅"
echo "   - 获取用户列表: ✅"
echo "   - 更新用户信息: ✅"
echo "   - 监控指标: ✅"
